package com.twetec.cms.adapter.pc.backend.interceptor;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.common.util.jwt.JWTUtil;
import com.twetec.cms.model.vo.ucenter.UserVO;
import com.twetec.cms.service.ucenter.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 拦截器-用户身份检查
 */
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从http头中获取Authorization
        String authorization = request.getHeader("Authorization");

        // 2、如果authorization未接收到或格式不正确，则停止后续，返回错误信息
        if (StringUtils.isBlank(authorization) || !authorization.startsWith("Bearer ")){
            // 响应，响应信息
            response(response, R.failureUserAuth().msg("用户身份无效，请重新登录"));
            return false;
        }

        // 如果authorization存在，则解析出jwt
        String jwt = StringUtils.substringAfter(authorization, "Bearer ");

//        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNDMzOTk4NTc3MjQ4MDk2MjU4IiwiaWF0IjoxNjMyODI2NTA1LCJzdWIiOiJUaGhQQmkzaE9UOWlZTVc5Q0ZCUEpnPT0iLCJpc3MiOiJYTS1VTklPTi1DTVMiLCJleHAiOjE2MzI4MjgzMDV9.-YYx7iXRGoF7oraM3PwnzfTV2Hg_XRVutbq6aXM_b18";

        // 如果jwt为空，则停止后续，返回错误信息
        if (StringUtils.isBlank(jwt)) {
            response(response, R.failureUserAuth().msg("用户身份错误，请重新登录"));
            return false;
        }

        // jwt存在，进行身份签名验证，如果jwt有效，且未过期
        if (!JWTUtil.checkTokenValid(jwt)) {
            response(response, R.failureUserAuth().msg("用户身份无效，请重新登录"));
            return false;
        }

        long userId = JWTUtil.parseUserId(jwt).longValue();

        UserVO user = userService.getByUserId(userId);
        if (null == user) {
            response(response, R.failureUserAuth().msg("用户身份无效，请重新登录"));
            return false;
        }

        // 将用户信息存入全局
        request.setAttribute("userId", userId);

        // jwt存在，且未过期,则继续后面的处理
        return true;
    }

    private void response(HttpServletResponse response, R r) throws Exception {
        // 设置字符编码
        response.setContentType("application/json; charset=utf-8");

        // jackson类库中的重要类，可以将对象、数据集转化为json数据。
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        String rJSONStr = objectMapper.writeValueAsString(r);
        // 返回的数据
        PrintWriter printWriter = response.getWriter();
        printWriter.print(rJSONStr);
        printWriter.close();

        response.flushBuffer();
    }
}
